import Vue from "vue";
import Vuex from 'vuex'
import {getMenus} from "@/layout/config";

Vue.use(Vuex)

const handleStore = (store) => {
    const global = JSON.parse(localStorage.getItem("global") || "{}");
    if (global.token) {
        store.replaceState({...store.state, ...global})
    }
    store.subscribe((updateParams, state) => {
        localStorage.setItem("global", JSON.stringify(state))
    });
}

export default new Vuex.Store({
    state: {
        token: '',
        roles: []
    },
    getters: {
        currentMenus(state) {
            const currentRoles = state.roles;
            const getCurrentMenus = (menus = getMenus()) => {
                return menus.filter(item => {
                    if (item.children){
                        item.children = getCurrentMenus(item.children);
                    }
                    return item.roles.some(val  => currentRoles.includes(val))
                })
            }
            return getCurrentMenus();
        }
    },
    mutations: {
        setUserInfo(state, {token}) {
            state.token = token
        },
        setRoles(state, {roles}) {
            state.roles = roles
        }
    },
    actions: {},
    modules: {},
    plugins: [handleStore]
})
